package org.ydsw.data.manage.schedule;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.ydsw.data.manage.entity.ScheduleJobEntity;
import org.ydsw.data.manage.service.ScheduleJobService;


import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Title: 启动JAR包时启动定时任务类 </p>
 * <p>Description：
 * 从数据库配置信息启动定时任务
 * </p>
 * @author admin
 * @version 1.0.0
 */
@Slf4j
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ScheduleJobService scheduleJobService;

    /**
     * 重复执行计数
     */
    public static AtomicInteger count = new AtomicInteger(0);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 防止重复执行
        if (event.getApplicationContext().getParent() == null && count.incrementAndGet() <= 1) {
            int taskCount = initTask();
            log.info("初始化成功任务个数："+taskCount);
        }
    }

    /**
     * 初始化任务个数
     * 从数据库配置信息中，依次读取需要启动定时任务的配置信息
     * @return 返回同时执行任务个数
     */
    public int initTask() {
        //从数据库中获取配置信息
        List<ScheduleJobEntity> scheduleJobList = scheduleJobService.queryList();
        log.info("initTask size : {}, scheduleJobList : {}", scheduleJobList.size(), JSONArray.toJSONString(scheduleJobList));

        if (CollectionUtils.isNotEmpty(scheduleJobList)) {
            scheduleJobList.forEach(scheduleJob -> {
                //设置定时执行頻率触发器
                CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
                //如果不存在，则创建
                if (cronTrigger == null) {
                    ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
                } else {
                    ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
                }
            });
        } else {
            log.info("未识别到可运行的任务，请检查配置表的配置信息！");
        }
        return scheduleJobList.size();
    }

}
